Page({
  data: {
    countDownVisible: false,
    mobile: '13488888888',
    code: '123456'
  },
  onLoad({
    redirectURL
  }) {
    this.redirectURL = redirectURL
  },
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0
    })
  },
  verifyMobile() {
    const pattern = /^1[3-9][0-9]{9}$/
    const isValid = pattern.test(this.data.mobile.trim())
    if (!isValid) {
      wx.utils.toast('手机号不合法')
    }
    return isValid
  },
  verifyCode() {
    // 验证码为6位数字
    const reg = /^\d{6}$/
    // 验证验证码
    const valid = reg.test(this.data.code.trim())
    // 验证结果提示
    if (!valid) wx.utils.toast('请检查验证码是否正确!')
    // 返回验证结果
    return valid
  },
  async getCode() {
    if (!this.verifyMobile()) return
    const {
      code
    } = await wx.http({
      url: `/code?mobile=${this.data.mobile}`
    })
    if (code !== 10000) {
      return wx.utils.toast('验证码发送失败,稍后重试')
    } else {
      wx.utils.toast('验证码发送成功')
      this.setData({
        countDownVisible: true
      })
    }
  },
  async submitForm() {
    if (!this.verifyCode()) return
    if (!this.verifyMobile()) return

    const {
      code,
      data
    } = await wx.http({
      method: 'post',
      url: '/login',
      data: {
        mobile: this.data.mobile,
        code: this.data.code
      }
    })
    console.log(code, data)
    if (code !== 10000) return wx.utils.toast()

    console.log('目的地', this.redirectURL)
    // 将token记录下来, 然后跳转
    const app = getApp()
    // app.token = data.token
    // // 存起来, 方便下次进入小程序使用
    // wx.setStorageSync('token', data.token)
    app.setToken(data.token, data.refreshToken)

    wx.redirectTo({
      url: this.redirectURL
    })
  }
})
